package com.dlc.shop.user.common.listener;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.dlc.shop.bean.event.UserDestroyEvent;
import com.dlc.shop.bean.model.UserAddr;
import com.dlc.shop.common.enums.SysTypeEnum;
import com.dlc.shop.security.common.bo.UidInfoBO;
import com.dlc.shop.security.common.dao.AppConnectMapper;
import com.dlc.shop.security.common.manager.TokenStore;
import com.dlc.shop.security.common.model.AppConnect;
import com.dlc.shop.security.common.service.AppConnectService;
import com.dlc.shop.service.UserAddrService;
import com.dlc.shop.user.common.model.*;
import com.dlc.shop.user.common.service.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * @author chiley
 * @date 2022/9/8 11:11
 */
@Slf4j
@Component("userDestroyListener")
@AllArgsConstructor
public class UserDestroyListener {

    private UserAddrService userAddrService;
    private UserGrowthLogService userGrowthLogService;
    private UserScoreDetailService userScoreDetailService;
    private UserScoreLockService userScoreLockService;
    private UserScoreLogService userScoreLogService;
    private UserTagUserService userTagUserService;
    private AppConnectService appConnectService;
    private TokenStore tokenStore;

    private final AppConnectMapper appConnectMapper;
    private final PopupUserLogService popupUserLogService;

    /**
     * 用户注销时,删除相关数据
     */
    @EventListener(UserDestroyEvent.class)
    @Transactional(rollbackFor = Exception.class)
    public void userDestroyListener(UserDestroyEvent event) {
        String userId = event.getUserId();
        userAddrService.remove(new LambdaQueryWrapper<UserAddr>().eq(UserAddr::getUserId, userId));
        userGrowthLogService.remove(new LambdaQueryWrapper<UserGrowthLog>().eq(UserGrowthLog::getUserId, userId));
        userScoreDetailService.remove(new LambdaQueryWrapper<UserScoreDetail>().eq(UserScoreDetail::getUserId, userId));
        userScoreLockService.remove(new LambdaQueryWrapper<UserScoreLock>().eq(UserScoreLock::getUserId, userId));
        userScoreLogService.remove(new LambdaQueryWrapper<UserScoreLog>().eq(UserScoreLog::getUserId, userId));
        userTagUserService.remove(new LambdaQueryWrapper<UserTagUser>().eq(UserTagUser::getUserId, userId));
        appConnectService.remove(new LambdaQueryWrapper<AppConnect>().eq(AppConnect::getUserId, userId));
        popupUserLogService.remove(new LambdaQueryWrapper<PopupUserLog>().eq(PopupUserLog::getUserId, userId));
        tokenStore.deleteTokenByUidInfo(new UidInfoBO(SysTypeEnum.ORDINARY, userId));
        // 解除社交账号的绑定
        appConnectMapper.unBindUserByUserId(userId);
    }
}
